﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace PLock {
	partial class MasterSetDlg : Form {
		public MasterSetDlg(bool reset) {
			InitializeComponent();

			if (reset)
				labelTop.Text = "Enter a new master password to re-encrypt all entries in the data folder.";
			_reset = reset;
		}

		private bool _reset;

		private void MasterEntryDlg_Load(object sender, EventArgs e) {
			textBoxPass.Select();
		}

		private void textBoxPass_TextChanged(object sender, EventArgs e) {
			buttonOK.Enabled = PasswordDlg.IsValidPassword(textBoxPass.Text) &&
							   PasswordDlg.IsValidPassword(textBoxPassConfirm.Text) &&
							   textBoxPass.Text == textBoxPassConfirm.Text;
		}

		private void buttonOK_Click(object sender, EventArgs e) {
			if (_reset) {
				LabelCache.InvalidateCache();
				byte[] salt = PasswordDlg.NewSalt();
				try {
					foreach (string label in LabelCache.GetLabels()) {
						Entry entry = LabelCache.GetEntry(label);
						entry.SetWriteKey(textBoxPass.Text, salt);
						string val = entry.ReadPassword();
						if (val != "")
							entry.WritePassword(val);
						val = entry.ReadUsername();
						if (val != "")
							entry.WriteUsername(val);
						val = entry.ReadSnippet();
						if (val != "")
							entry.WriteSnippet(val);
						val = null;
					}
				} catch (Exception ex) {
					MessageBox.Show(this, ex.Message, "Error Writing Entry", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
				PasswordDlg.ForgetPassword();
				try {
					PasswordDlg.SaveDigest(textBoxPass.Text, salt);
				} catch (Exception ex) {
					MessageBox.Show(this, ex.Message, "Error Writing Master Digest", MessageBoxButtons.OK, MessageBoxIcon.Error);
					return;
				}
			} else
				PasswordDlg.SaveDigest(textBoxPass.Text, PasswordDlg.NewSalt());
			this.DialogResult = DialogResult.OK;
		}
	}
}
